package com.sghj.pageviews.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sghj.pageviews.entity.PageView;
import com.sghj.pageviews.entity.SysAccessLog;
import com.sghj.pageviews.mapper.SysAccessLogMapper;
import com.sghj.pageviews.service.SysAccessLogService;
import com.sghj.utils.IpUtils;
import com.sghj.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 日志记录表 服务实现类
 * </p>
 *
 * @author zk
 * @since 2022-02-07
 */
@Service
public class SysAccessLogServiceImpl extends ServiceImpl<SysAccessLogMapper, SysAccessLog> implements SysAccessLogService {
    @Autowired
    private SysAccessLogMapper sysAccessLogMapper;

    @Override
    public int insertLog(String token) {
        //插入日志
        SysAccessLog sys_log = new SysAccessLog();
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        Integer userid = JwtUtils.getIdByToken(token);
        //Integer userid = 1;//应该从session中获取当前登录人的id，这里简单模拟下

        sys_log.setUserId(userid);

        sys_log.setCreateTime(new Timestamp(new Date().getTime()));

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        sys_log.setAccessYear(sdf1.format(new Date()));
        sys_log.setAccessDay(sdf2.format(new Date()));

        sys_log.setInterviewerIp(IpUtils.getIpAddr(request));
        // TODO Auto-generated method stub
        return sysAccessLogMapper.insert(sys_log);
    }

    @Override
    public PageView getViewResult() {
        PageView result = new PageView();

        //获取当前时间信息并规范化
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

        String nowyear = sdf1.format(new Date());
        String nowday = sdf2.format(new Date());

        result.setSum(baseMapper.getSumpageviews());
        result.setYearSum(baseMapper.getYearpageviews(nowyear));
        result.setDaySum(baseMapper.getDaypageviews(nowday));

        return result;
    }
}
